/**
 * 
 */
package com.julang.check.controller;

import com.julang.check.utils.CommonData;
import com.julang.check.utils.MessageInfo;
import com.julang.check.utils.Result;
import com.julang.check.utils.SingnalData;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Date;

import static com.julang.check.utils.CommonData.POINT;
import static com.julang.check.utils.MessageInfo.FILENOTEXIST;

/**
 * @author zhailiang
 *
 */
@RestController
@RequestMapping("/file")
public class FileController {


	@PostMapping
	public Result<String> upload(MultipartFile file) throws Exception {
		long s = System.currentTimeMillis();
		Result<String> result = new Result();
		String originalFilename = file.getOriginalFilename();
		if (!originalFilename.contains(POINT)) {
			return result.fail(CommonData.FAIL, MessageInfo.FILENOTEXIST, "");
		}
		System.out.println("收到文件名字： " + file.getOriginalFilename());
		String[] datas = originalFilename.split("\\.");
		String suffix = "." + datas[datas.length - 1];
		File localFile = new File(SingnalData.filePath, System.currentTimeMillis() + suffix);
		file.transferTo(localFile);
		System.out.println("上传文件耗时：" + (System.currentTimeMillis() - s) + "  毫秒");
		return result.success(MessageInfo.UPLOADFILESUCCESSINFO, localFile.getAbsolutePath());
	}

	@GetMapping("/{id}")
	public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
		try (InputStream inputStream = new FileInputStream(new File(SingnalData.filePath, id + ".txt"));
				OutputStream outputStream = response.getOutputStream();) {
			response.setContentType("application/x-download");
			response.addHeader("Content-Disposition", "attachment;filename=test.txt");
			IOUtils.copy(inputStream, outputStream);
			outputStream.flush();
		} 

	}

}
